/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package co.com.ces4.produccion.jpa.controllers;

import co.com.ces4.produccion.jpa.controllers.exceptions.IllegalOrphanException;
import co.com.ces4.produccion.jpa.controllers.exceptions.NonexistentEntityException;
import co.com.ces4.produccion.jpa.entities.LineaProduccion;
import java.io.Serializable;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import co.com.ces4.produccion.jpa.entities.ArticuloLinea;
import co.com.ces4.produccion.jpa.entities.ArticuloLineaPK;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author usuario
 */
public class LineaProduccionJpaController implements Serializable {

    public LineaProduccionJpaController(EntityManagerFactory emf) {
        this.emf = emf;
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public LineaProduccion create(LineaProduccion lineaProduccion) {
        List<ArticuloLinea> saveArticuloLineaList = lineaProduccion.getArticuloLineaList();

        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            lineaProduccion.setArticuloLineaList(new ArrayList<ArticuloLinea>());
            em.persist(lineaProduccion);
            em.getTransaction().commit();


            if (!saveArticuloLineaList.isEmpty()) {
                for (ArticuloLinea ArticuloLineaToSave : saveArticuloLineaList) {
                    ArticuloLineaToSave.setArticuloLineaPK(new ArticuloLineaPK(lineaProduccion.getNmid(), ArticuloLineaToSave.getArticulo().getDsid()));
                }
                lineaProduccion.setArticuloLineaList(saveArticuloLineaList);
            }

            return lineaProduccion;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(LineaProduccion lineaProduccion) throws IllegalOrphanException, NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            LineaProduccion persistentLineaProduccion = em.find(LineaProduccion.class, lineaProduccion.getNmid());
            List<ArticuloLinea> articuloLineaListOld = persistentLineaProduccion.getArticuloLineaList();
            List<ArticuloLinea> articuloLineaListNew = lineaProduccion.getArticuloLineaList();
            List<String> illegalOrphanMessages = null;
            for (ArticuloLinea articuloLineaListOldArticuloLinea : articuloLineaListOld) {
                if (!articuloLineaListNew.contains(articuloLineaListOldArticuloLinea)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain ArticuloLinea " + articuloLineaListOldArticuloLinea + " since its lineaProduccion field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            List<ArticuloLinea> attachedArticuloLineaListNew = new ArrayList<ArticuloLinea>();
            for (ArticuloLinea articuloLineaListNewArticuloLineaToAttach : articuloLineaListNew) {
                articuloLineaListNewArticuloLineaToAttach = em.getReference(articuloLineaListNewArticuloLineaToAttach.getClass(), articuloLineaListNewArticuloLineaToAttach.getArticuloLineaPK());
                attachedArticuloLineaListNew.add(articuloLineaListNewArticuloLineaToAttach);
            }
            articuloLineaListNew = attachedArticuloLineaListNew;
            lineaProduccion.setArticuloLineaList(articuloLineaListNew);
            lineaProduccion = em.merge(lineaProduccion);
            for (ArticuloLinea articuloLineaListNewArticuloLinea : articuloLineaListNew) {
                if (!articuloLineaListOld.contains(articuloLineaListNewArticuloLinea)) {
                    LineaProduccion oldLineaProduccionOfArticuloLineaListNewArticuloLinea = articuloLineaListNewArticuloLinea.getLineaProduccion();
                    articuloLineaListNewArticuloLinea.setLineaProduccion(lineaProduccion);
                    articuloLineaListNewArticuloLinea = em.merge(articuloLineaListNewArticuloLinea);
                    if (oldLineaProduccionOfArticuloLineaListNewArticuloLinea != null && !oldLineaProduccionOfArticuloLineaListNewArticuloLinea.equals(lineaProduccion)) {
                        oldLineaProduccionOfArticuloLineaListNewArticuloLinea.getArticuloLineaList().remove(articuloLineaListNewArticuloLinea);
                        oldLineaProduccionOfArticuloLineaListNewArticuloLinea = em.merge(oldLineaProduccionOfArticuloLineaListNewArticuloLinea);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = lineaProduccion.getNmid();
                if (findLineaProduccion(id) == null) {
                    throw new NonexistentEntityException("The lineaProduccion with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            LineaProduccion lineaProduccion;
            try {
                lineaProduccion = em.getReference(LineaProduccion.class, id);
                lineaProduccion.getNmid();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The lineaProduccion with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            List<ArticuloLinea> articuloLineaListOrphanCheck = lineaProduccion.getArticuloLineaList();
            for (ArticuloLinea articuloLineaListOrphanCheckArticuloLinea : articuloLineaListOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This LineaProduccion (" + lineaProduccion + ") cannot be destroyed since the ArticuloLinea " + articuloLineaListOrphanCheckArticuloLinea + " in its articuloLineaList field has a non-nullable lineaProduccion field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            em.remove(lineaProduccion);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<LineaProduccion> findLineaProduccionEntities() {
        return findLineaProduccionEntities(true, -1, -1);
    }

    public List<LineaProduccion> findLineaProduccionEntities(int maxResults, int firstResult) {
        return findLineaProduccionEntities(false, maxResults, firstResult);
    }

    private List<LineaProduccion> findLineaProduccionEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(LineaProduccion.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public LineaProduccion findLineaProduccion(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(LineaProduccion.class, id);
        } finally {
            em.close();
        }
    }

    public int getLineaProduccionCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<LineaProduccion> rt = cq.from(LineaProduccion.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }

    public List<LineaProduccion> getLineaList(String codigo, String descripcion) {
        EntityManager em = getEntityManager();
        try {
            StringBuilder sb = new StringBuilder("SELECT linea FROM LineaProduccion linea WHERE 1=1 ");
            if (codigo != null) {
                sb.append("AND (linea.nmid = :NMID ");
                if (descripcion != null) {
                    sb.append("AND linea.dsdescripcion LIKE :DSDESCRIPCION");
                }
                sb.append(")");
            } else if (descripcion != null) {
                sb.append("AND linea.dsdescripcion LIKE :DSDESCRIPCION");
            }

            Query query = em.createQuery(sb.toString());
            if (codigo != null) {
                query.setParameter("NMID", Integer.parseInt(codigo));
            }
            if (descripcion != null) {
                query.setParameter("DSDESCRIPCION", "%" + descripcion + "%");
            }

            List<LineaProduccion> lineasProduccion = query.getResultList();
            return lineasProduccion;
        } finally {
            em.close();
        }
    }
}
